package day11.handler.simpleChannelHandler.request;

import day11.packet.request.MessageRequestPacket;
import day11.packet.response.MessageResponsePacket;
import day11.util.session.Session;
import day11.util.session.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;

/**
 * @author chenshijie
 * @date 2023/12/26 13:20
 */

public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket messageRequestPacket) throws Exception {
        receiveMessage(ctx, messageRequestPacket);
    }

    private static MessageResponsePacket receiveMessage(ChannelHandlerContext ctx, MessageRequestPacket messageRequestPacket) {
        // 1. 获得消息发送方的会话信息
        Session session = SessionUtil.getSession(ctx.channel());

        // 2. 通过消息发送方的会话信息构造要发送的消息
        MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
        messageResponsePacket.setVersion(messageRequestPacket.getVersion());
        messageResponsePacket.setFromUserId(session.getUserId());
        messageResponsePacket.setUserName(session.getUserName());
        messageResponsePacket.setMessage(messageRequestPacket.getMessage());

        System.out.println(new Date() + ": 收到客户端"+ session.getUserId() + "发给" + messageRequestPacket.getToUserId() + "的消息: " + messageRequestPacket.getMessage());

        // 3. 获得消息接收方的channel
        Channel toUserChannel = SessionUtil.getChannel(messageRequestPacket.getToUserId());
        System.out.println(toUserChannel);

        // 4. 将消息发送给消息接收方
        if (toUserChannel != null && SessionUtil.hasLogin(toUserChannel)) {
            toUserChannel.writeAndFlush(messageResponsePacket);
        } else {
            System.err.println("【" + messageRequestPacket.getToUserId() + "】不在线，发送失败");
        }


        return messageResponsePacket;
    }
}
